package com.dc.spring.init;

import com.dc.spring.bean.FirstBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;


public class MyApplicationContentBean implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    Logger logger = LoggerFactory.getLogger(this.getClass().getName()) ;
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        logger.info("myStart MyApplicationContentBean initialize");
        //第一种
//        if(applicationContext instanceof GenericApplicationContext ){
//            GenericApplicationContext applicationContext1 = (GenericApplicationContext) applicationContext;
//            logger.info("MyApplicationContentBean initialize");
//            applicationContext1.registerBean("frirstBean", FirstBean.class, () -> new FirstBean("Hello, World!"));
//            //不需要手动调用 报错程序会自动调用
//            //applicationContext1.refresh();
//        }


        if (applicationContext instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext;
            logger.info("myStart MyApplicationContentBean initialize");
            // 使用 GenericBeanDefinition 注册 Bean
            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(FirstBean.class);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue("Hello, World!");

            registry.registerBeanDefinition("firstBean", beanDefinition);
        }

    }
}
